//
//  UIViewController+ImagePicker.m
//  lxtxAppBackstage
//
//  Created by com.chetuba on 15/7/16.
//  Copyright (c) 2015年 Lxtx. All rights reserved.
//

#define WARNINGCAMER @"该设备没有相机功能"
#define WARNINGABLUM @"开心在缐现在没有访问您的照片的权限,请到系统'设置'-'隐私'-'照片'中开启"


#import "UIViewController+ImagePicker.h"


static char keyImagePickerBlock;
static char keyIsRound;
@implementation UIViewController (ImagePicker)

/**
 OC中的关联就是在已有类的基础上添加对象参数。来扩展原有的类，需要引入#import <objc/runtime.h>头文件。关联是基于一个key来区分不同的关联。
 常用函数: objc_setAssociatedObject     设置关联
 objc_getAssociatedObject     获取关联
 objc_removeAssociatedObjects 移除关联
 */

- (UIImagePickerController *)imagePicker{
    
    UIImagePickerController *Picker = objc_getAssociatedObject(self, _cmd);
    
    if (!Picker) {
        Picker = [[UIImagePickerController alloc] init];
        
        Picker.allowsEditing = YES;
        
        Picker.delegate = self;
        
        objc_setAssociatedObject(self, _cmd, Picker, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return Picker;
}

- (void)setImagePicker:(UIImagePickerController *)imagePicker{
    
}

- (BOOL)isRound{
    
    NSNumber *IsRound = objc_getAssociatedObject(self, &keyIsRound);
    return IsRound.boolValue;
    
}
- (void)setIsRound:(BOOL)isRound{
    
    if (isRound != self.isRound) {
        
        self.isRound = NO;
        // 存储新的
        [self willChangeValueForKey:@"isRoundKey"]; // KVO
        objc_setAssociatedObject(self, &keyIsRound, [NSNumber numberWithBool:isRound], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [self didChangeValueForKey:@"isRoundKey"]; // KVO
    }
}

///打开选择
- (void)openChoiceWithCompleteBlock:(FinishPickingMediaWithInfo)block isRound:(BOOL)isRound{
    
    if (block) {
        ////移除所有关联
        //objc_removeAssociatedObjects(self);
        /**
         1 创建关联（源对象，关键字，关联的对象和一个关联策略。)
         2 关键字是一个void类型的指针。每一个关联的关键字必须是唯一的。通常都是会采用静态变量来作为关键字。
         3 关联策略表明了相关的对象是通过赋值，保留引用还是复制的方式进行关联的；关联是原子的还是非原子的。这里的关联策略和声明属性时的很类似。
         */
        objc_setAssociatedObject(self, &keyImagePickerBlock, block, OBJC_ASSOCIATION_COPY);
        
    }
    
    self.isRound = isRound;
    
    UIAlertController *alertController = [UIAlertController showActionSheetwithTitle:@"请选择方式" Message:nil];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        [self openSystemCamera];
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self openSystemAblum];
        
        
    }]];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
    
}
- (void)openChoiceWithCompleteBlock:(FinishPickingMediaWithInfo)block{
    
    [self openChoiceWithCompleteBlock:block isRound:NO];


}

- (void)openSystemAblum
{
    ALAuthorizationStatus  status = [ALAssetsLibrary authorizationStatus];
    if(status == ALAuthorizationStatusRestricted ||
       status == ALAuthorizationStatusDenied)
    {
        
        
        [UIAlertController showAlertwithMessage:WARNINGABLUM withVC:self withBlock:nil];
        

        return;
    }
    
    
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController: self.imagePicker animated:YES completion:nil];

}
- (void)openSystemCamera
{
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        

        [UIAlertController showAlertwithMessage:WARNINGCAMER withVC:self withBlock:nil];
        
        
        return;
    }
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
 
    if (self.isRound) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
        
        if ([navigationController.viewControllers count] == 3 && ([[[[navigationController.viewControllers objectAtIndex:2] class] description] isEqualToString:@"PUUIImageViewController"] || [[[[navigationController.viewControllers objectAtIndex:2] class] description] isEqualToString:@"PLUIImageViewController"])){
            
            [self addCircleOverlayToImagePicker:viewController];
        }
    }
    
    
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (self.isRound) {
    
        if ([navigationController.viewControllers count] == 3 && ([[[[navigationController.viewControllers objectAtIndex:2] class] description] isEqualToString:@"PUUIImageViewController"] || [[[[navigationController.viewControllers objectAtIndex:2] class] description] isEqualToString:@"PLUIImageViewController"])){
            
            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
        }
    }
    
    

}


-(void)addCircleOverlayToImagePicker:(UIViewController*)viewController
{
    UIColor *circleColor = [UIColor clearColor];
    UIColor *maskColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
    
    CGFloat screenHeight = [[UIScreen mainScreen] bounds].size.height;
    CGFloat screenWidth = [[UIScreen mainScreen] bounds].size.width;
    
    UIView *plCropOverlayCropView; //The default crop overlay view, we wan't to hide it and show our circular one
    UIView *plCropOverlayBottomBar; //On iPhone this is the bar with "cancel" and "choose" buttons, on Ipad it's an Image View with a label saying "Scale and move"
    
    //Subviews hirearchy is different in iPad/iPhone:
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        
        plCropOverlayCropView = [viewController.view.subviews objectAtIndex:1];
        plCropOverlayBottomBar = [[[[viewController.view subviews] objectAtIndex:1] subviews] objectAtIndex:1];
        
        //Protect against iOS changes...
        if (! [[[plCropOverlayCropView class] description] isEqualToString:@"PLCropOverlay"]){
            DLog(@"Warning - Image Picker with circle overlay: PLCropOverlay not found");
            return;
        }
        if (! [[[plCropOverlayBottomBar class] description] isEqualToString:@"UIImageView"]){
            DLog(@"Warning - Image Picker with circle overlay: BottomBar not found");
            return;
        }
    }
    else{
        plCropOverlayCropView = [[[viewController.view.subviews objectAtIndex:1] subviews] firstObject];
        plCropOverlayBottomBar = [[[[viewController.view subviews] objectAtIndex:1] subviews] objectAtIndex:1];
        
        //Protect against iOS changes...
        if (! [[[plCropOverlayCropView class] description] isEqualToString:@"PLCropOverlayCropView"]){
            DLog(@"Image Picker with circle overlay: PLCropOverlayCropView not found");
            return;
        }
        if (! [[[plCropOverlayBottomBar class] description] isEqualToString:@"PLCropOverlayBottomBar"]){
            DLog(@"Image Picker with circle overlay: PLCropOverlayBottomBar not found");
            return;
        }
    }
    
    //It seems that everything is ok, we found the CropOverlayCropView and the CropOverlayBottomBar
    
    plCropOverlayCropView.hidden = YES; //Hide default CropView
    
    CAShapeLayer *circleLayer = [CAShapeLayer layer];
    //Center the circleLayer frame:
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0.0f, screenHeight/2 - screenWidth/2, screenWidth, screenWidth)];
    circlePath.usesEvenOddFillRule = YES;
    circleLayer.path = [circlePath CGPath];
    circleLayer.fillColor = circleColor.CGColor;
    //Mask layer frame: it begins on y=0 and ends on y = plCropOverlayBottomBar.origin.y
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, screenWidth, screenHeight - 72.5) cornerRadius:0];
    [maskPath appendPath:circlePath];
    maskPath.usesEvenOddFillRule = YES;
    
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.path = maskPath.CGPath;
    maskLayer.fillRule = kCAFillRuleEvenOdd;
    maskLayer.fillColor = maskColor.CGColor;
    [viewController.view.layer addSublayer:maskLayer];
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone){
        //On iPhone add an hint label on top saying "scale and move" or whatever you want
        UILabel *cropLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, screenWidth, 50)];
        [cropLabel setText:@"选择头像"]; //You should localize it
        [cropLabel setTextAlignment:NSTextAlignmentCenter];
        [cropLabel setTextColor:[UIColor whiteColor]];
        [viewController.view addSubview:cropLabel];
    }
    else{ //On iPad re-add the overlayBottomBar with the label "scale and move" because we set its parent to hidden (it's a subview of PLCropOverlay)
        [viewController.view addSubview:plCropOverlayBottomBar];
    }
}

#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    ///获取关联的对象，通过关键字。
    FinishPickingMediaWithInfo block = objc_getAssociatedObject(self, &keyImagePickerBlock);
    if (block) {
        ///block传值
        block(info);
    }
    
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
     [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma ============================关于相册和摄像头的判断
// 判断设备是否有摄像头

- (BOOL) isCameraAvailable{
    
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    
}


// 前面的摄像头是否可用

- (BOOL) isFrontCameraAvailable{
    
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
    
}

// 后面的摄像头是否可用

- (BOOL) isRearCameraAvailable{
    
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
    
}
// 判断是否支持某种多媒体类型：拍照，视频

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    
    __block BOOL result = NO;
    
    if ([paramMediaType length] == 0){
        
        NSLog(@"Media type is empty.");
        
        return NO;
        
    }
    
    NSArray *availableMediaTypes =[UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    
    [availableMediaTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL*stop) {
        
        NSString *mediaType = (NSString *)obj;
        
        if ([mediaType isEqualToString:paramMediaType]){
            
            result = YES;
            
            *stop= YES;
            
        }
        
        
        
    }];
    
    return result;
    
}


// 检查摄像头是否支持录像

- (BOOL) doesCameraSupportShootingVideos{
    
    return [self cameraSupportsMedia:( NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypeCamera];
    
}


// 检查摄像头是否支持拍照

- (BOOL) doesCameraSupportTakingPhotos{
    
    return [self cameraSupportsMedia:( NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
    
}

#pragma mark - 相册文件选取相关

// 相册是否可用

- (BOOL)isPhotoLibraryAvailable{
    
    return [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary];
    
}


// 是否可以在相册中选择视频

- (BOOL) canUserPickVideosFromPhotoLibrary{
    
    return [self cameraSupportsMedia:( NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    
}


// 是否可以在相册中选择视频

- (BOOL) canUserPickPhotosFromPhotoLibrary{
    
    return [self cameraSupportsMedia:( NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    
}


@end
